package com.paipaideli.ui.pay;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;
import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.MyApplication;
import com.paipaideli.R;
import com.paipaideli.alipay.AuthResult;
import com.paipaideli.alipay.PayResult;
import com.paipaideli.alipay.util.OrderInfoUtil2_0;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.base.IEventBus;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.TStatusView;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.common.utils.preferrnces.FastData;
import com.paipaideli.common.views.CommonDialogView;
import com.paipaideli.ui.MainActivity;
import com.paipaideli.ui.login.LoginActivity;
import com.paipaideli.ui.mine.address.AddAddressActivity;
import com.paipaideli.ui.mine.head.AssetsActivity;
import com.paipaideli.ui.mine.head.InvestActivity;
import com.paipaideli.ui.mine.order.OrderDetailActivity;
import com.paipaideli.ui.mine.safety.event.LogoutEvent;
import com.paipaideli.ui.price.PriceActivity;
import com.paipaideli.wxapi.event.PayEvent;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 重要说明：
 * <p>
 * 本 Demo 只是为了方便直接向商户展示支付宝的整个支付流程，所以将加签过程直接放在客户端完成
 * （包括 OrderInfoUtil2_0_HK 和 OrderInfoUtil2_0）。
 * <p>
 * 在真实 App 中，私钥（如 RSA_PRIVATE 等）数据严禁放在客户端，同时加签过程务必要放在服务端完成，
 * 否则可能造成商户私密数据泄露或被盗用，造成不必要的资金损失，面临各种安全风险。
 * <p>
 * Warning:
 * <p>
 * For demonstration purpose, the assembling and signing of the request parameters are done on
 * the client side in this demo application.
 * <p>
 * However, in practice, both assembling and signing must be carried out on the server side.
 */
public class PayActivity extends BasePresenterActivity implements IEventBus {

    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "2019090566957443";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "2088531083901143";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "paiapideli";

    /**
     * pkcs8 格式的商户私钥。
     * <p>
     * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * RSA2_PRIVATE。
     * <p>
     * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDUATIsf28kC5AtuGNS/GO754drxUQlgeHKOIQB2hLEhvlL6HzUq/2b2/XVFWDdaozoAZkOTgqlRWRixu9eKX2HPuI3DtoSHPzM7n4IpnfBdSfAlZw+VAlkd9KHjTYzncJuH+bYpfJf9in2uQo0abxCIYDOAyrZ7ITr4S9npGR2USc0LnzrWPa56rSFe9ttGHj7/o7vv8z+WrSaNA7CJiVPXgdHYFqEp8OdItQGWiGoBQEBENrmTwzJ44pD0zX7O8LelhIxQ9lxLiXMpeWoFeTL6H7FbnZkQcsBS/cxVgW2Bnl4VDpWeef8R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Zl3JwUXMY7nPel4Kx9ZqQVW03go99ke2XBejXaGUoUgDmNt7VOkCgYEA6LlTvz9TZJPObXainx9O5q6bto2+Vm360rBJAndtBhYt/TuO9OKf7N2nYQxSQPY+CuZKLQE6REIES+Y0U/bFW5LnYLX9RGHtGj4b3KqdsI2NUrhkO5ln2u8AgLSy7V0SJal0lPHU5Vubs3nlhN4M02/POKVlToSO1I8kmDCciiECgYEAiLuDSRbUnHCS/EjD2LL0vR7LJbfQA4cxB3uIB9YalajaUFeykYQvY24gBHA+jAcypChwy7cVpRReRloxXYq/4QjNR4F72ZDkoHBL/dbtKdtS8qRbm7aYvO6Cegd5WHltGfeCv3NODNcZW489yYXlyHVJZXtyjF5Ff75yZXgiOqkCgYEArVcMx9A1Hx7wjJvmuLqrHCtGFA0zjlDQmAlx+AJYFEaE7q9j5Ya/M8BNIX357iT7RUcOTMMzURAS/y1yIHAXxAOBj4k+IacG4ZsNSalTVuO4Nbrd/X5f2rRWHYd6Fk5Sa/bxvNb7ifJX4LCUggiaaQpIwJqBAKC/ehc8XJcoocECgYEAhp3vt94oHROSx9OitAVykMh2ZZGa1zqx7jVy870pP/tbt1bqRGzCwt+Fj8wuZxaz+NQi03XyI0CY/cmXv3K3Bi4IvXZTAbRPmwaH/l9JLaOWRVaPaKnPSUM+RJVi3e24RH8pxoDjwtCgvohOos2Hh/q4Me9bS6h0TMcKd5ulGN4=";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private IWXAPI api;
    // APP_ID 替换为你的应用从官方网站申请到的合法appId
    public static final String APP_ID = "wxf90fd221278b8b0f";


    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout topBack;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.tv_pay_money)
    TextView tvPayMoney;
    @BindView(R.id.tv_pay_ye)
    TextView tvPayYe;
    @BindView(R.id.bg_statusview)
    TStatusView bg_statusview;
    @BindView(R.id.rel_pay_ye)
    RelativeLayout rel_pay_ye;

    private String orderId;
    private String amount;
    private String outTradeNo;
    private String which;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        AlipayQuery();//支付宝回调查询
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(PayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            Toast.makeText(PayActivity.this, "支付取消", Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    public int getContentView() {
        return R.layout.activity_pay;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        topTitle.setText("支付");

        api = WXAPIFactory.createWXAPI(this, APP_ID);
        //  api.registerApp(APP_ID);
        //返回
        topBack.setOnClickListener(o ->
                finish()
        );
        which = getIntent().getStringExtra("which");
        if (which.equals("1")) {
            try {
                orderId = getIntent().getStringExtra("orderId");
            } catch (Exception e) {
                e.getMessage();
            }
            bg_statusview.showLoading();
            getPrice();//获取余额
        } else {
            amount = getIntent().getStringExtra("amount");
            tvPayMoney.setText("￥" + amount);
            rel_pay_ye.setVisibility(View.GONE);
        }
    }

    private void getPrice() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("id", orderId);
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().price(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    bg_statusview.finish();
                    if (request.code.equals("200")) {
                        amount = request.data.orderPrice;
                        tvPayMoney.setText("￥" + amount);
                        tvPayYe.setText("(账户余额：￥" + request.data.remainder + ")");
                    } else {
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }

    /**
     * 余额支付
     */
    public void payYE(View v) {
        bg_statusview.showLoading();
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("orderId", orderId);
            requestData.put("payType", "2");
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().blancePay(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    bg_statusview.finish();
                    if (request.code.equals("200")) {
                        showTwo();
                    } else {
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }

    private void showTwo() {
        final CommonDialogView dialog = new CommonDialogView(PayActivity.this);
        dialog.setMessage("支付成功")
                .setTitle("温馨提示")
                .setSingle(true).setOnClickBottomListener(new CommonDialogView.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                finish();
                dialog.dismiss();
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();

            }
        }).show();
    }

    /**
     * 支付宝支付业务示例
     */
    public void payV2(View v) {
        bg_statusview.showLoading();
        JSONObject requestData = new JSONObject();
        try {
            if (which.equals("1")) {
                requestData.put("orderId", orderId);
                requestData.put("payType", "2");
            } else {
                requestData.put("amount", amount);
                requestData.put("payType", "1");
            }
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().AlipayPay(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    bg_statusview.finish();
                    if (request.code.equals("200")) {
                        final String alipayInfo = request.data.orderString;
                        outTradeNo = request.data.outTradeNo;
                        FastData.setOutTradeNo(outTradeNo);
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                // 构造PayTask 对象
                                PayTask alipay = new PayTask(PayActivity.this);
                                // 调用支付接口，获取支付结果
                                String result = alipay.pay(alipayInfo, true);
                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };
                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    } else {
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }


    private void AlipayQuery() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("outTradeNo", FastData.getOutTradeNo());
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().AlipayQuery(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    bg_statusview.finish();
                    if (request.getCode().equals("200")) {
                        if (which.equals("1")) {
                            showTwo();
                        } else {
                            if (MyApplication.isAlipay == 1) {
                                MainActivity.openSingleTop(this);
                            } else {
                                Intent intent = new Intent(PayActivity.this, AssetsActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        }
                    } else {
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }

    /**
     * 微信支付
     */
    public void payWX(View v) {
        bg_statusview.showLoading();
        JSONObject requestData = new JSONObject();
        try {
            if (which.equals("1")) {
                requestData.put("orderId", orderId);
                requestData.put("payType", "2");
            } else {
                requestData.put("amount", amount);
                requestData.put("payType", "1");
            }
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().WXpayPay(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    bg_statusview.finish();
                    if (request.code.equals("200")) {
                        outTradeNo = request.data.outTradeNo;
                        FastData.setOutTradeNo(outTradeNo);
                        PayReq req = new PayReq();
                        req.appId = request.data.appid;
                        req.nonceStr = request.data.noncestr;
                        req.packageValue = request.data.packageValue;
                        req.partnerId = request.data.partnerid;
                        req.prepayId = request.data.prepayid;
                        req.timeStamp = request.data.timestamp;
                        req.sign = request.data.sign;
                        api.sendReq(req);
                    } else {
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }


    //关闭当前页面
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEvent(PayEvent payEvent) {
        showTwo();
    }

}
